package models

import (
	"database/sql"
	"database/sql/driver"
	"encoding/json"
)

type JsonString string

func (js JsonString) MarshalJSON() ([]byte, error) {
	return []byte(js), nil
}

func (js *JsonString) UnmarshalJSON(json []byte) error {
	var str = string(json)
	*js = JsonString(str)
	return nil
}

type NullString sql.NullString

func (t NullString) MarshalJSON() ([]byte, error) {
	if !t.Valid {
		return []byte("null"), nil
	}
	return json.Marshal(t.String)
}

func (t *NullString) UnmarshalJSON(b []byte) error {
	t.Valid = false
	var str = string(b)
	if str == "null" || str == "" {
		return nil
	}
	if err := json.Unmarshal(b, &t.String); err != nil {
		return err
	}
	t.Valid = true
	return nil
}

// 将数据库中取出的数据，赋值给目标类型
func (t *NullString) Scan(v interface{}) error {
	return (*sql.NullString)(t).Scan(v)
}

//Value implements the driver Valuer interface.
func (t NullString) Value() (driver.Value, error) {
	return (sql.NullString)(t).Value()
}
